﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Media;
using DeepEarth.Map.Core;
using DeepEarth.Map.Core.Utilities;
using DeepEarth.Map.Core.Tiling; 

#if !WINDOWS_PHONE
using System.ComponentModel.Composition;
#endif

namespace DeepEarth.Map.TileSources
{
#if !WINDOWS_PHONE
    [Export(typeof(BaseTileSource))] 
#endif
    public sealed class NearMapTileSource: BaseTileSource
    {
        private const int DefaultMaxZoomLevel = 21;
        private const int DefaultTileSize = 256;
        private const string TilePath = "http://web{0}.nearmap.com/maps/hl=en&x={1}&y={2}&z={3}&nml={4}&s=Ga";

        //Constructor Called by XAML instanciation; Wait for MapMode to be set to initialize services
        public NearMapTileSource()
            : base(NearMapTileSourceFactory.PhotoMap, (int)Math.Pow(2, DefaultMaxZoomLevel) * DefaultTileSize,
                   (int)Math.Pow(2, DefaultMaxZoomLevel) * DefaultTileSize,
                   DefaultTileSize,
                   DefaultTileSize,
                    0)
        {
        }

		internal NearMapTileSource(MapMode mode)
            : base(mode, (int)Math.Pow(2, DefaultMaxZoomLevel) * DefaultTileSize,
                (int)Math.Pow(2, DefaultMaxZoomLevel) * DefaultTileSize,
                DefaultTileSize,
                DefaultTileSize,
                0)
        {
        }

        private bool Intersects(Rect a, Rect b)
        {
            a.Intersect(b);

            return !a.IsEmpty;
        }

        protected override string GetTileUri(int zoom, int tilePositionX, int tilePositionY)
        {
            var quadKey = TileXYToQuadKey(tilePositionX, tilePositionY, zoom);
            var modeKey = Mode.ProviderKey;
            var url = string.Format(TilePath,
                                    quadKey.Substring(quadKey.Length - 1),
                                    tilePositionX,
                                    tilePositionY,
                                    zoom,
                                    modeKey);

            if (Mode == NearMapTileSourceFactory.PhotoMap && Date != null)
                url = url + "&nmd=" + Date.Value.ToString("yyyyMMdd");

            return url;
        }

        private static string TileXYToQuadKey(int tileX, int tileY, int levelOfDetail)
        {
            var quadKey = new StringBuilder();
            for (var i = levelOfDetail; i > 0; i--)
            {
                var digit = '0';
                var mask = 1 << (i - 1);
                if ((tileX & mask) != 0) digit++;
                if ((tileY & mask) != 0)
                {
                    digit++;
                    digit++;
                }
                quadKey.Append(digit);
            }
            return quadKey.ToString();
        }

	}
}